The Visual Basic Scripting Edition (VBScript) language is a subset of Microsoft Visual Basic for Applications (VBA) and Microsoft Visual Basic. You can use VBScript for interfacing both ActiveX controls and Java applets, as well as writing stand-alone scripts that act directly upon the browser object. The syntax (how you write the code) is clear and logical in the vast majority of cases; there are no cryptic symbols or constructs. In fact, much of the syntax predates even Visual Basic with its ancestral roots placed firmly in the early Basic languages. The vast majority of the algorithms and procedures used by the scripting language engine behind the scenes are tried and tested, giving you a robust basis and foundation to work from.
In the many hours I have spent working with VBScript, I have yet to encounter anything in the language that I would call a bug, which is probably due to the length of time that Visual Basic and its cousins have been around. Compare my VBScript experience with newer scripting languages that appear to be fraught with problems. I mention this not to advertise for those nice people at Microsoft, but to let you know that you can confidently program in VBScript. When an error does rear its ugly head, the error is probably yours and not the scripting engine's.
In this chapter, you'll see how you can create powerful scripts for your Web pages quickly and easily using the VBScript language. Even if you are experienced in Visual Basic or VBA, I still recommend that you read this chapter and the rest of the chapters in Part II regarding the VBScript language because there are a few differences in the implementation of the VBScript language that might take you by surprise.
The most logical place to start with any programming language is the data types. Data types are crucial because they define how the computer stores data while the program is executing. The computer needs to know what type of data you are handling (for example, is x a string or a number?) so that it can allocate memory space. Different data types take up different amounts of memory, as you can see from the following list of fundamental data types:
VBScript makes it easy for you to work with any of these data types without placing instructions in your program about which data type you need to use. VBScript uses what's known as a variant data type.
A variant is a special data type that can contain any of the fundamental data types shown in the preceding list. It dynamically allocates memory space according to which data subtype is required. This means that you don't have to explicitly declare variables as a particular fundamental type (as you do with the majority of programming languages). A variant takes care of that for you.
As you can see from the following sample code, VBScript does not require you to tell it what type of data you want to place inside the variables Qty and ProductName. You simply assign your values to Qty and ProductName and let the variant data type do the rest.
<SCRIPT LANGUAGE = "vbscript"> <!-- Qty = 162 ProductName = "Paper Clip" --> </SCRIPT>
Although you do not need to assign the data type in VBScript,
on many occasions you need to know what type of data the variant
is holding. You can use the built-in VarType function
to determine how the data in a variant is treated. Table 4.1 shows
the return values of the VarType function and the corresponding
contents of the variant.
Data Type Held in Variant | |
Empty (uninitialized) | |
Null (no valid data) | |
Integer | |
Long (long integer) | |
Single (single-precision floating-point) | |
Double (double-precision floating-point) | |
Date | |
String | |
Object | |
Error | |
Boolean | |
Array of variant | |
Byte | |
Array |
To illustrate using the VarType function, I've expanded the short example used previously:
<HTML> <HEAD> <SCRIPT LANGUAGE = "vbscript"> <!-- Sub Button1_OnClick Qty = 162 ProductName = "Paper Clip" Alert "Qty is a type " & VarType(Qty) & " Variant" Alert "ProductName is a type " & VarType(ProductName) & " Variant" End Sub --> </SCRIPT> </HEAD> <BODY BGCOLOR="white"> <CENTER> <INPUT TYPE=BUTTON NAME="Button1" VALUE="Click Me"> </CENTER> </BODY> </HTML>
When you run this HTML file with the browser and click the button, it shows two alert boxes, one after the other. The alert boxes report that Qty is a type 2 (see Table 4.1) integer and ProductName is a type 8 string data type variant.
If variant does all the work for you, you shouldn't need to worry about what data is held, and you shouldn't have to convert data types, right? Wrong! Look at the following example:
<HTML> <HEAD> <TITLE>Add two numbers</TITLE> <SCRIPT LANGUAGE="vbscript"> <!-- Sub Button1_OnClick FirstData = Document.Form1.Text1.Value SecondData = Document.Form1.Text2.Value Document.Form1.Text3.Value = FirstData + SecondData End Sub --> </SCRIPT> </HEAD> <BODY BGCOLOR="white"> <CENTER> <FORM NAME="Form1"> Enter a Number <INPUT TYPE="text" NAME="Text1"><P> Enter a Number <INPUT TYPE="text" NAME="Text2"><P> <INPUT TYPE="button" NAME="Button1" VALUE="Click Me to add"><P> The Result is <INPUT TYPE="text" NAME="Text3"> </FORM> </CENTER> </BODY> </HTML>
You are asked to enter a number in the top text box and a number in the middle text box. When you click the button, a simple addition is performed on the two numbers:
Sub Button1_OnClick FirstData = Document.Form1.Text1.Value SecondData = Document.Form1.Text2.Value Document.Form1.Text3.Value = FirstData + SecondData End Sub
If you don't have a browser handy, Figure 4.1 shows you what happens.
Figure 4.1 : Trying to add two numbers together from an HTML form.
Surprised? Both numbers were added together-sort of-but the data types are strings, so 100 + 100 is not 200, but 100100. The reason for this is that HTML forms can return only string data; they never return numerical data. Variant treated the incoming data correctly. It's just that nobody told it you really wanted numbers!
Help is at hand: VBScript has a range of functions that allow you to convert data to all manner of types:
You use the conversion functions like this:
result = CInt(variable)
Here's the previous example, reworked slightly to convert the incoming data to double-precision numerical data types:
Sub Button1_OnClick FirstData = CDbl(Document.Form1.Text1.Value) SecondData = CDbl(Document.Form1.Text2.Value) Document.Form1.Text3.Value = FirstData + SecondData End Sub
The addition now works fine and dandy as long as the user remembers to make a numerical entry. 100 + 100 really does equal 200; however (there's always a however), if the user enters something such as Fred and 100, an error is generated, and the program comes to a grinding halt-which is not good. In Chapter 6, "Checking Form Data," you'll see how the IsNumeric function traps errant data entry.
In this section, you'll see how to handle data within your script by declaring variables and constants. But before you get down to it, you should first get acquainted with what variables and constants are.
A variable is a name that you give to an area of memory-a memory location-which holds a value used in your program. It is a placeholder that is easily remembered and recognizable. For example, you wouldn't want to remember that the contents of the Text1 text box are in memory location 00AC0744:002606C8, but it's easy to remember MyData.
Another problem is that data moves around in memory, so you'd have to manually keep up with its new location, which might be virtually impossible. When you use a variable name, the language engine looks in a table of variable names and goes to the current memory location of the data. It is also good programming practice to denote what type of data you expect to use within the variable, which is done by using a three-letter lowercase prefix like this:
intMyIntegerData lngMyLongData strMyStringData
Variables can have their values changed during their lifetimes, as the name suggests. You can amend them at will, but sometimes you need to use a fixed value throughout your script, and this is where constants come in.
In strict terms, VBScript has no constants. A constant is a variable whose value is fixed throughout its lifetime. In other flavors of Visual Basic, you declare a constant explicitly with the CONST directive, and if any part of your program attempts to change the value, a runtime error is generated.
VBScript has no CONST directive. Any constants are "virtual," so the safest way to declare a constant is to use the code convention of uppercase characters for your constant's name, like this:
MY_CONSTANT
An addition to the normal convention is to always use more than one word for the constant name and separate them with an underscore. The underscore separates them visually from HTML elements that should be uppercase but are always only a single word.
The next concept you need to know about constants and variables is that where you define a variable or constant affects where you have access to that variable or constant and how long its lifetime is. This designation is called scope.
The scope of a variable or constant determines whether all subroutines and procedures within the HTML document can use it or only one subroutine can use it. Look at this example:
1:<SCRIPT LANGUAGE="vbscript"> 2:<!-- 3:Sub MySubRoutine() 4:dim intMyInteger 5:intMyInteger = 5 6:Document.Form1.Text3.Value = CInt(Document.Form1.Text1.Value) + intMyInteger 7:End Sub 8:--> 9:</SCRIPT>
Line 4 declares the variable intMyInteger, and line 5 assigns a value to it. This variable is only available to the MySubRoutine procedure; when the procedure is complete at line 7, the variable intMyInteger ceases to exist. Any calls to a variable called intMyInteger in other scripts on the page force the creation of a completely new variable. This is an example of local scope.
Now look at this example:
1:<SCRIPT LANGUAGE="vbscript"> 2:<!-- 3:dim strMyString 4:Sub MySubRoutine() 6:strMyString = Document.Form1.Text1.Value 7:Document.Form1.Text2.Value = UCase(strMyString) 8:End Sub 9:Sub AnotherSubRoutine() 10:Alert strMyString 11:End Sub 12:--> 13:</SCRIPT>
Notice this time that the variable strMyString is declared on line 3, outside of either of the two subroutines, but of course within the <SCRIPT> tag. On line 6, the contents of Text1 are assigned to strMyString. In line 10, the value of strMyString is displayed to the user in an alert box. Assuming that MySubRoutine is executed before AnotherSubRoutine, the alert box shows the contents of Text1 because strMyString is still active. It was not destroyed as you saw in the last example because it has script-level scope. It is available to all the subroutines and functions on the page.
To declare a variable with script-level scope, you simply declare it outside of a subroutine. Look at this next example:
<SCRIPT LANGUAGE="vbscript"> <!-- Sub MyButton_OnClick Alert "Hello World" End Sub --> </SCRIPT> <SCRIPT LANGUAGE="vbscript"> <!-- dim intMyInteger Sub AnotherButton_OnClick Alert "Hello Again" End Sub --> </SCRIPT>
This time, intMyInteger is declared outside of any subroutines or functions but appears within the second <SCRIPT> block. This change doesn't matter. The script engine still treats intMyInteger as a variable with script-level scope because the script engine gathers all the scripts on the page prior to creating the in-memory program.
You will often encounter the term global variable, which is exactly the same as a script-level scoped variable, but it's easier to say!
Later in this chapter, you'll see how to use the ActiveX Control Pad to declare a global variable, which in VBScript is the same as a global constant.
Earlier, you saw that you do not need to strictly declare variables
because the variant data type takes care of the nitty gritty.
However, you might write complex scripts with several different
functions passing data around. If others will use and possibly
maintain your script, it is good programming practice to declare
variables explicitly.
NOTE |
You can force the script to shout at you if you don't declare a variable by using the OPTION EXPLICIT directive under the first <SCRIPT> tag. This instructs the scripting engine to generate a runtime error if it encounters an undeclared variable. |
As you saw from the short code snippets earlier in this chapter, the way to declare either a variable or a constant in VBScript is by using the Dim keyword. The following code shows a full working example to demonstrate the use of local and global (or script-level) constants and variables. The line numbers are included purely for reference, so don't type them into your HTML file.
1:<HTML> 2:<HEAD><TITLE>SCOPE</TITLE> 3:<SCRIPT LANGUAGE="vbscript"> 4:<!-- 5:Dim intGlobalVariable 6:Dim MY_GLOBAL_CONSTANT 7:MY_GLOBAL_CONSTANT = 3 8:Sub Button1_OnClick 9: Dim intLocalVariable 10: intLocalVariable = CInt(Document.Form1.Text1.Value) 11: intLocalVariable = intLocalVariable * MY_GLOBAL_CONSTANT 12: Alert intLocalVariable 13: intGlobalVariable = intLocalVariable 14:End Sub 15:Sub Button2_OnClick 16: Dim intLocalConstant 17: intLocalConstant = 6 18: intGlobalVariable = intGlobalVariable / intLocalConstant å + MY_GLOBAL_CONSTANT 19: Alert intGlobalVariable 20: End Sub --> </SCRIPT> </HEAD> <BODY BGCOLOR="white"> <CENTER> <FORM NAME="Form1"> Please enter a number <INPUT TYPE="text" NAME="Text1"><P> <INPUT TYPE="button" NAME="Button1" VALUE="Click Me"><P> <INPUT TYPE="button" NAME="Button2" VALUE="Then Click Me"> </FORM> </CENTER> </BODY> </HTML>
As this page loads into the browser, the script engine automatically executes lines 5 through 7. This means that the global variable intGlobalVariable is available for any of the scripts on the page, as is the global constant intGlobalConstant, which had the number 3 assigned to it in line 7.
When you load this page (scope.htm) into the browser, you are asked to enter a number into the text box. When you click the first button, the Button1_OnClick event handler springs into action.
As the Button1_OnClick event handler begins execution in lines 8 and 9, a new intLocalVariable variable is created. The value that you entered into the text box is then converted to an integer and assigned to the local variable in line 10. Line 11 uses the global constant (which has a value of 3) to perform a simple calculation and returns the result to the same local variable. The value of the local variable is then shown to the world through the Alert box in line 12. The final line of this procedure copies the result to the global variable. As the subroutine ends, the local variable is destroyed in memory and no longer exists; however, you've ensured that its final value lives on in the global variable.
Click Button2 to fire the Button2_OnClick event. Line 16 declares a global constant. You can see that there is no difference in the language between constants and variables; the only reason you know it's a constant (apart from its name, in this case) is the clue from the coding convention. A number is assigned to the local constant so that using the constant is the same as using that number-in this case, 6.
Line 18 performs a simple calculation using the local constant and both the global variable and constant. Line 19 then displays the result. As before, when the procedure ends in Line 20, the local constant is destroyed. Just to prove that the values of the global constant and variable are still there, click the second button again. This time, the result of the first calculation from Button 1 is held in the global variable and is still available for use.
When you understand global or local constants and variables, you have the basis to do some neat things, and it really isn't rocket science. The ActiveX Control Pad enables you to easily declare global variables.
The Script Wizard of the ActiveX Control Pad has a built-in object for global variables and constants, making it as easy as point and click to create global variables for your scripts. Follow the creation of a simple Web page that uses a global variable.
Open the ActiveX Control Pad, and in the default HTML page, amend the following lines-just to make the thing look a little better:
Figure 4.4 : The HTML with the global variable definition and script.
The Script Wizard creates two different script blocks, one in
the head section that defines the global variable and a second
just above the command button definition that contains the main
script.
TIP |
If you want to create this variable as a constant, you move the line that assigns its value to appear just below the Dim statement in the top script block. |
Save the file as variable.htm and run it with your browser.
One of the main uses of any programming language is comparing values and performing calculations based on those values and data. VBScript offers you a rich set of comparison and arithmetical operators to perform all types of operations from the very simple to the highly complex.
Comparison operators need very little introduction; they are the symbols used to compare one value with another value and return either True or False. The comparison operators available in VBScript are as follows:
I used the word argument in the preceding definitions. An argument can be a single variable or value or a complete calculation in itself, as shown in the following examples:
If x = 10 Then If y > ((10 * 2) - (30.333 / 76)) Then
The result of a comparison is always a Boolean True or False.
Arithmetical operators in VBScript act exactly as you would expect.
The following list presents no surprises:
Addition | |
Subtraction | |
Division | |
Multiplication | |
Exponentiation | |
Integer division | |
Modulo arithmetic | |
String concatenation |
The next application uses comparison and arithmetic operators. Because it's a long application, I won't discuss every last line and object, only the areas relevant to this chapter.
Figure 4.5 shows the application called the Mr Frosty Air Conditioner Web page. Visitors to the site can enter the dimensions of their rooms in meters; the script calculates the volume of the room and then compares the volume with the maximum capacities of the Mr Frosty Air Conditioner range.
Figure 4.5 : The Mr Frosty Air Conditioners Webpage.
The following is the full source code for the page:
<HTML> <HEAD> <TITLE>Mr Frosty Air Conditioners</TITLE> </HEAD> <BODY BGCOLOR="aqua"> <FONT FACE="arial" SIZE=2> <CENTER> <H2>Mr Frosty Air Conditioners</H2> <P> <FORM NAME="Form1"> <TABLE> <TD><FONT SIZE=2>Enter the <B>Width</B><BR> of your room <TD><FONT SIZE=2>Enter the <B>Length</B><BR> of your room <TD><FONT SIZE=2>Enter the <B>Height</B><BR> of your room <TR> <TD><INPUT TYPE=text NAME="roomwidth">M <TD><INPUT TYPE=text NAME="roomlength">M <TD><INPUT TYPE=text NAME="roomheight">M <TR> </TABLE> <P> <SCRIPT LANGUAGE="VBScript"> <!-- dim MODELA_MAX dim MODELB_MAX dim MODELC_MAX MODELA_MAX = 130 MODELB_MAX = 500 MODELC_MAX = 1000 Function WhichModel(lngRoomVolume) If lngRoomVolume < MODELA_MAX then WhichModel = "Mini Syberia" Exit Function End If If lngRoomVolume < MODELB_MAX then WhichModel = "Midi Artic" Exit Function End If If lngRoomVolume < MODELC_MAX then WhichModel = "Maxi Antarctica" Exit Function End If WhichModel = "Golly Jeepers that's BIG!!" End Function Sub CommandButton1_Click() dim intW dim intL dim intH dim lngVol dim strMsg intW = CInt(Document.Form1.roomwidth.value) intL = CInt(Document.Form1.roomlength.value) intH = CInt(Document.Form1.roomheight.value) lngVol = intW * intL * intH strMsg = "Your room is " & CStr(lngVol) & " cubic Metres" strMsg = strMsg & Chr(10) & Chr(13) strMsg = strMsg & "You need our " & WhichModel(lngVol) & " Model" Label1.Caption = strMsg end sub --> </SCRIPT> <OBJECT ID="CommandButton1" WIDTH=120 HEIGHT=36 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57"> <PARAM NAME="ForeColor" VALUE="0"> <PARAM NAME="VariousPropertyBits" VALUE="268435483"> <PARAM NAME="Caption" VALUE="CALCULATE"> <PARAM NAME="Size" VALUE="3175;952"> <PARAM NAME="FontEffects" VALUE="1073741825"> <PARAM NAME="FontHeight" VALUE="240"> <PARAM NAME="FontCharSet" VALUE="0"> <PARAM NAME="FontPitchAndFamily" VALUE="2"> <PARAM NAME="ParagraphAlign" VALUE="3"> <PARAM NAME="FontWeight" VALUE="700"> </OBJECT> </FORM> <P> <OBJECT ID="Label1" WIDTH=533 HEIGHT=80 CLASSID="CLSID:978C9E23-D4B0-11CE-Bf2D-00AA003f40D0"> <PARAM NAME="ForeColor" VALUE="16711680"> <PARAM NAME="BackColor" VALUE="16776960"> <PARAM NAME="VariousPropertyBits" VALUE="276824083"> <PARAM NAME="Caption" VALUE="Enter the dimensions of your room, åthen click CALCULATE to discover which is the best Mr Frosty Air Conditioner for you!!"> <PARAM NAME="Size" VALUE="14111;2116"> <PARAM NAME="FontEffects" VALUE="1073741827"> <PARAM NAME="FontHeight" VALUE="280"> <PARAM NAME="FontCharSet" VALUE="0"> <PARAM NAME="FontPitchAndFamily" VALUE="2"> <PARAM NAME="ParagraphAlign" VALUE="3"> <PARAM NAME="FontWeight" VALUE="700"> </OBJECT> </BODY> </HTML>
The application uses a combination of HTML controls and ActiveX controls. The first script you encounter is the definition of the constants used for holding the maximum values for the model range:
<SCRIPT LANGUAGE="VBScript"> <!-- dim MODELA_MAX dim MODELB_MAX dim MODELC_MAX MODELA_MAX = 130 MODELB_MAX = 500 MODELC_MAX = 1000
Follow the script not as it appears on the page, but in the logical sequence that starts with the user clicking the button. This application provides no check to ensure that the data entered is the correct type. For example, if someone types in Four instead of 4, you're in trouble.
The event handler for the Click event starts with a declaration of several variables that are used within the procedure:
Sub CommandButton1_Click() dim intW dim intL dim intH dim lngVol dim strMsg
Remember that all data coming from an HTML form is string data, so the first job is to convert the incoming data to numerical data so that you can perform calculations on it:
intW = CInt(Document.Form1.roomwidth.value) intL = CInt(Document.Form1.roomlength.value) intH = CInt(Document.Form1.roomheight.value)
Now, you can calculate the room's volume by simply multiplying all the values together:
lngVol = intW * intL * intH
The next section starts to build the message that is displayed to the user. Note that the numerical room volume variable (lngVol) is converted to a string:
strMsg = "Your room is " & CStr(lngVol) & " cubic Metres" strMsg = strMsg & Chr(10) & Chr(13)
The next line makes a call to the function WhichModel. WhichModel compares the volume to the maximum volumes of the product range. If the room volume is less than the product's maximum capacity, it is safe to recommend the product. Starting with the smallest unit, the comparisons continue until one of the If...Then statements returns True. At this point, the model name is returned to the line calling the function, effectively replacing the function call with the product name:
strMsg = strMsg & "You need our " & WhichModel(lngVol) & " Model" Function WhichModel(lngRoomVolume) If lngRoomVolume < MODELA_MAX then WhichModel = "Mini Syberia" Exit Function End If If lngRoomVolume < MODELB_MAX then WhichModel = "Midi Artic" Exit Function End If If lngRoomVolume < MODELC_MAX then WhichModel = "Maxi Antarctica" Exit Function End If WhichModel = "Golly Jeepers that's BIG!!" End Function
Finally, the message that has been created is copied to the label caption and displayed on-screen, as shown in Figure 4.6.
Figure 4.6 : Mr Frosty makes his recommendation.
In this chapter, you started to build the foundations of VBScript programming by learning the data type variant and its subtypes, how to find out what data is held in variant using VarType, and also how to convert that data using the conversion functions.
You used variables and constants and learned the difference between global and local scope and how it is defined within the program. Finally, you looked at how you can use VBScript to compare values and perform calculations and other arithmetic.
Now you have seen the foundations of programming in VBScript. To start creating real applications, take at look at the following chapters:
You mentioned naming conventions earlier. What are they, and why do we have them? | |
Naming or coding conventions allow different people to read the same programming code and understand quickly what is happening within the script or program. It also helps you later, when you need to make amendments to a script that you wrote possibly many months previously. It's simply a common set of notations. When you see a name such as MY_COLOR, you know that it's a constant. Other conventions cover variables that can use an abbreviation of the data subtype in lowercase as the first three characters of the name. For example, an integer variable can be called intMyVar. | |
I've used other programming languages before. With them, I have to specify what type of data I'm using in the variable and stick rigidly to that. Why is VBScript so different? | |
As you have seen, the variant data type almost eliminates the need to define the type of data you will hold within a particular variable. Microsoft wanted VBScript to be as easy as possible to use, so that first-time programmers who had arrived at VBScript from HTML could create scripts with the minimum amount of fuss and bother. With the variant data type, they have achieved just that. |